package org.WhyMCA.WhyMCANews;

/**
@author Danilo '' Riso >> danilo DOT riso AT gmail DOT com
* @author Androidiani Dev Team
* @version 1.0
*/

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.WhyMCA.WhyMCANews.Splashscreen;
import org.WhyMCA.Utils.DialogMgr.DialogCallback;
import org.WhyMCA.Utils.Global;
import org.WhyMCA.Utils.XMLParser;
import org.WhyMCA.Utils.DialogMgr;
import org.WhyMCA.WhyMCANews.R;
import org.WhyMCA.Utils.PreferencesMgr;
import org.WhyMCA.Adapters.WhyMCAAdapter;
import org.WhyMCA.Models.WhyMCANewsModel;
import org.WhyMCA.Services.WhyMCAService;
import org.WhyMCA.Services.WhyMCAService.OnServiceListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import org.xmlpull.v1.XmlPullParserException;

public class WhyMCANews extends Activity implements OnClickListener, DialogCallback, Runnable, OnServiceListener {

	private static ArrayList<WhyMCANewsModel> _nlwhymca;
	private SharedPreferences.Editor _prefed;
	private static SharedPreferences _sharpref;
	private Intent _splash, _whymcaservice, _settings, _credits;
	private static long _timemill;
	private int type;
	private byte[] _readb;
	private boolean _refresh;
	private static String _ilxml;
	private WhyMCAAdapter _nadapter;
	private ListView _newslist;
			
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Global.setCtx(this);
        setContentView(R.layout.main);
              
        checkNetwork();
        createElements();
        viewSplash();
    
    }
    
    public void onResume(Bundle savedInstanceState) {

    	checkUpdates();
    	    	
    }
    
    private void checkNetwork() {
    	
    	ConnectivityManager _cm = (ConnectivityManager) Global.getCtx().getSystemService(Context.CONNECTIVITY_SERVICE);
    	
    	if(!_cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected() && !_cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()){
    		
    		DialogMgr.noNetworkAlert(this);
    		
    	}
    	
    }
    
    private void viewSplash() {
    	
    	_splash = new Intent(Global.getCtx(), Splashscreen.class);
    	startActivity(_splash);
    	
    }
    
    private void startWhyMCAService() {
    	
    	if(_whymcaservice == null) {
    		
    		_whymcaservice = new Intent(Global.getCtx(), WhyMCAService.class); 
    		startService(_whymcaservice);
    	} else {
    		stopService(_whymcaservice); 
    		startService(_whymcaservice);
    	}
    	
    }
    public void createElements() {
    	
    	_newslist = (ListView) findViewById(R.id.listView1);
    	WhyMCAService.setCallBack(this);
    	WhyMCAService.setMainIntent(this.getIntent());
    	_settings = new Intent(Global.getCtx(), Settings.class);
    	_credits = new Intent(Global.getCtx(), CreditsActivity.class);
    	startWhyMCAService();
    	
    	_sharpref = Global.getCtx().getSharedPreferences("WhyMCA", 0);
    	_prefed = _sharpref.edit();
    	                
        PreferencesMgr.createElements();
    	loadLocalXML();
        
	}
        
    public void loadLocalXML() {
    	
    	if(PreferencesMgr.checkXmlCurrent()) {
    		
    		_ilxml = PreferencesMgr.getXmlCurrent();
    		    		
    	} else {
    		
    		InputStream _ilis;
        	        	
        	_ilis = (Global.getResources().openRawResource(R.raw.rss));
        	try {
    			_readb = new byte[_ilis.available()];
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        	try {
        		_ilis.read(_readb);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		_ilxml = new String(_readb);
    		PreferencesMgr.setXmlCurrent(_ilxml);
        	        	
    	}
    		
    	sendILInfo();
		_refresh = true;
    	
    }
    
    public void onStart(){
    	super.onStart();
              	
    }
                
    public void onPause(){
    	super.onPause();
    	    	 	   
 	}
                  
	public void onClick(View v) {
			
		//Login.resetPref();
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	 moveTaskToBack(true);
	         return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}

	
	public void run() {
		        
    }
			
	@Override
	public void onDialogClicked(boolean result) {
		
		stopService(_whymcaservice);
		this.finish();
		
	}
	
	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, 0, 0, "Exit");
	    menu.add(0, 1, 0, "Impostazioni");
	    menu.add(0, 2, 0, "Crediti");
	    return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
	    
		switch (item.getItemId()) {
	    
	    	case 0:
	    		
	    		this.finish();
	    	
	    		return true;
	    
	    	case 1:
	        
	    		Settings.setWhyMCAService(_whymcaservice);
	    		stopService(_whymcaservice);
	    		Global.setCtx(this);
	    		startActivity(_settings);
	    		
	    		return true;
	    
	    	case 2:
		        
	    		Global.setCtx(this);
	    		startActivity(_credits);
	    		
	    		return true;
	    		
		}
	 
		return false;
	
	}

	@Override
	public void onDataReceived() {
		
		System.out.println("Ricevo i dati");
		
		if(this.hasWindowFocus())
		
			checkUpdates();
					
	}
	
	public void onWindowFocusChanged (boolean hasFocus) {
    	
    	if(hasFocus) {
    		
    		WhyMCAService.setWindowsFocus(true);
    		checkUpdates();
    		
    	} else {
    		
    		WhyMCAService.setWindowsFocus(false);
    		
    	}
    	
    }
	
	public static void setModelObject(ArrayList<WhyMCANewsModel> nlwhymca) {
		
		_nlwhymca = nlwhymca;
		
	}
	
	public static ArrayList<WhyMCANewsModel> getModelObject() {
		
		return _nlwhymca;
		
	}
	
	/*
 	*Usa il gruppo di oggetti model creato dal service contenente le news
 	*/
    private void checkUpdates() {

    	this._nadapter = new WhyMCAAdapter(this, _nlwhymca);
    	_newslist.setAdapter(this._nadapter);
	
    }
	
	/*
 	*Invia l'XML contenente le news al parsatore
 	*/
    private void sendILInfo() {
	
    	try {
		
    		_nlwhymca = XMLParser.getNews(_ilxml);
    		    		
    		// Et voila
    		//Log.d("Status", Integer.toString(_news.size()));
    		this._nadapter = new WhyMCAAdapter(this, _nlwhymca);
    		_newslist.setAdapter(this._nadapter);
    	    		
    		//_llocality.setOnItemClickListener(this);
    		//setListAdapter(this._wdapter);
    		//getListView().setAdapter(this._wdapter);
    		    	  	    		
		
    	} catch (XmlPullParserException e) {
		
    		// Manca la gestione degli errori!!!
    		//TODO Auto-generated catch block
    		e.printStackTrace();
    	
    	} catch (IOException e) {
		
    		// MAnca la gestione degli errori!!!
    		//TODO Auto-generated catch block
        	e.printStackTrace();
        	
    	}
	
    }
	
}